import tornado.web
from tornado.options import options
import datetime
import pandas as pd
from PyWebsite3.common import float_2_percentage
import Core.Gadget as Gadget


class RenderManagerPageHandler(tornado.web.RequestHandler):
    def get(self, path):
        manager_symbol = path
        # manager_symbol = "30036316"
        database = options.database
        datetime_update = datetime.datetime.now()

        # 读取基金经理基础信息表
        manager_filter = {"manager_symbol": manager_symbol}
        manager_document_tmp = database.Find("derivative_data", "fund_manager_snapshot", filter=manager_filter)
        manager_document = manager_document_tmp[0]

        manager_document_tmp = database.Find("financial_data", "mutualfund_manager", filter=manager_filter)
        manager_document["resume"] = manager_document_tmp[0]["resume"]

        # 读取收益因子
        recent_date = Gadget.Find_Recent_Date(database, "derivative_data", "fund_manager_return_profile", datetime_update)
        filter = [("manager_symbol", manager_symbol),("date", recent_date)]
        manager_return_profile_document = database.Find("derivative_data", "fund_manager_return_profile", filter=filter, sort=[("date", 1)])
        for document in manager_return_profile_document:
            # 格式化处理
            float_2_percentage(manager_document, fields=["annualized_return", "excess_return"])
            document["manage_years"] = document["manage_days"] / 245

        manager_tenure_documents = database.Find("financial_data", "mutualfund_manager_tenure", filter=manager_filter)

        invest_type_list = ["bond", "total_stock", "stock", "mix",  "currency", "qdii", "alternative"]

        # 读取职业生涯曲线
        career_curve_list_dict = {}
        for invest_type in invest_type_list:
            df_daily_bar = database.GetDataFrame("derivative_data", "mutualfund_manager_daily_return",
                                                 filter=[("manager_symbol", manager_symbol), ("invest_type", invest_type)])
            if df_daily_bar.empty:
                continue
            #
            df_daily_bar["net_asset_value"] = pd.DataFrame.cumprod(df_daily_bar["daily_return"] + 1)
            df_daily_bar["s_date"] = df_daily_bar["date"].apply(lambda x: x.strftime('%Y-%m-%d'))
            daily_bar_document = {"invest_type": invest_type}
            daily_bar_document["date"] = list(df_daily_bar["s_date"])
            daily_bar_document["price"] = list(df_daily_bar["net_asset_value"])
            career_curve_list_dict[invest_type] = daily_bar_document

        # 读取分项能力
        manager_ability_dict = {}
        for invest_type in invest_type_list:
            manager_filter = [("invest_type", invest_type), ("manager_symbol", manager_symbol)]
            manager_documents = database.Find("derivative_data", "fund_manager_score", filter=manager_filter, sort=[("date", -1)])
            if len(manager_documents) > 0:
                manager_ability_document = manager_documents[0]
                manager_ability_dict[invest_type] = manager_ability_document

        #
        self.render("manager.html", manager_document=manager_document,
                    manager_return_profile_document=manager_return_profile_document,
                    daily_bar_document_total_stock=career_curve_list_dict.get("total_stock"),
                    daily_bar_document_stock=career_curve_list_dict.get("stock"),
                    daily_bar_document_mix=career_curve_list_dict.get("mix"),
                    daily_bar_document_bond=career_curve_list_dict.get("bond"),
                    manager_total_stock_ability_document=manager_ability_dict.get("total_stock"),
                    manager_bond_ability_document=manager_ability_dict.get("bond"),
                    manager_stock_ability_document=manager_ability_dict.get("stock"),
                    manager_mix_ability_document=manager_ability_dict.get("mix"),
                    manager_tenure_documents=manager_tenure_documents)

    def post(self, path):
        print("request url: %s" % path)